<template>
  <div v-loading="loading">
    <create-sections
      title="汇报信息">
      <wk-base-detail-section :list="reportFields">
        <div v-if="data.label == '汇报材料'" slot-scope="data" style="flex: 0 0 80%;">
          <wk-file-cell
            v-for="(file, fileIndex) in reportInfo.file"
            :key="fileIndex"
            :data="file"
            :list="reportInfo.file"
            :index="fileIndex" />
        </div>
      </wk-base-detail-section>
      <div v-if="status == 1" slot="header" class="wk-base-detail__more" style="text-align: right; width: 100%;">
        <el-button slot="more" type="text" @click="commandSelect('edit')">编辑</el-button>
      </div>
    </create-sections>

    <form-add-dialog
      ref="formAdddialog"
      :title="formAddTitle"
      :form.sync="formAddForm"
      :rules="formAddRules"
      :fields="formAddFields"
      :visible.sync="formAddDialogShow"
      @pass="uploadReportInfo"
    >
      <div class="contract-files">
        <wk-file-select
          style="display: inline-block; padding-bottom: 5px;"
          multiple
          @change="fileSelect"
        >
          <el-button type="primary" plain>上传附件</el-button>
        </wk-file-select>
        <wk-file-cell
          v-for="(file, fileIndex) in fileList"
          :key="fileIndex"
          :data="file"
          :list="fileList"
          :index="fileIndex"
          delete-show
          @delete="fileDelete" />
      </div>
    </form-add-dialog>
  </div>
</template>

<script>
import {
  executionReportSimpleDetailAPI,
  executionReportUpdateAPI
} from '@/api/oa/report'
import {
  adminFileUploadAPI,
  adminFileDeleteByIdAPI
} from '@/api/admin/file'

import CreateSections from '@/components/CreateSections'
import WkFileSelect from '@/components/NewCom/WkFile/Select'
import WkFileCell from '@/components/NewCom/WkFile/Cell'
import WkBaseDetailSection from '@/components/WkBaseDetail/WkBaseDetailSection'
import FormAddDialog from './FormAddDialog'
import { createEditor } from '@wangeditor/editor'

import { reportTypeOptions, baseModel } from '../model/report'
import { objDeepCopy } from '../../../../utils'

export default {
  name: 'ReportInfo',
  components: {
    CreateSections,
    WkBaseDetailSection,
    FormAddDialog,
    WkFileSelect,
    WkFileCell
  },
  props: {
    id: [String, Number],
    status: [String, Number]
  },
  data() {
    return {
      loading: false,
      reportInfo: {},
      reportFields: [],
      // 弹窗添加
      formAddTitle: '',
      formAddForm: {},
      formAddRules: {},
      formAddFields: [],
      formAddDialogShow: false,
      // 附件
      batchId: '',
      fileList: []
    }
  },

  computed: {},
  watch: {
    id: {
      handler() {
        this.getDetail()
      },
      immediate: true
    }
  },
  mounted() {
  },

  beforeDestroy() {},
  methods: {
    /**
     * 获取基础信息
     */
    getDetail() {
      this.loading = true
      executionReportSimpleDetailAPI(this.id)
        .then(res => {
          this.loading = false
          const data = res.data || []
          this.reportInfo = data
          this.reportFields = this.getCommonFieldListValue(data)
        }).catch(() => {
          this.loading = false
        })
    },

    /**
     *常规字段值
     */
    getCommonFieldListValue(data) {
      const list = []
      baseModel.field.forEach(field => {
        if (field.name == '汇报材料') {
          return
        }
        const temp = {}
        temp.label = field.name
        if (field.field === 'reportType') {
          temp.value = reportTypeOptions.find(item => item.value == data[field.field])[0] || ''
        } else if (field.field === 'submitStatus') {
          const status = data[field.field]
          if (status == 1) {
            temp.value = '暂存'
          } else {
            temp.value = '已提交'
          }
          // else if (status == 2) {
          //   temp.value = '按时提交'
          // } else if (status == 3) {
          //   temp.value = '延时补交'
          // }
        } else if (field.field === 'month') {
          temp.label = '周期'
          temp.value = data.targetYear + '年' + data.targetMonth + '月第' + data.targetWeek + '周'
        } else if (field.field === 'targetWeek') {
          return
        } else if (field.field === 'reportContent') {
          const value = JSON.parse(data[field.field]) || []
          const editor = createEditor()
          editor.children = value
          // 3. 获取 data
          const html = editor.getHtml()
          temp.value = html
          temp.html = true
          temp.span = 1
        } else if (field.field === 'ownerUserIds') {
          temp.value = data['ownerUserList'] ? data['ownerUserList'].map(item => item.realname).join(',') : ''
        } else {
          temp.value = data[field.field]
        }
        list.push(temp)
      })
      list.splice(3, 0, {
        label: '汇报材料',
        span: 1
      })
      return list
    },

    /**
     * 提交数据
     */
    uploadReportInfo() {
      const param = objDeepCopy(this.formAddForm)
      param.batchId = this.batchId
      param.reportContent = JSON.stringify(param.reportContent)
      executionReportUpdateAPI(param).then(res => {
        this.$message.success(`${this.formAddTitle}成功`)
        this.formAddDialogShow = false
        this.getDetail()
      }).catch(() => {
        this.formAddDialogShow = false
      })
    },

    /**
     * 编辑删除操作
     */
    commandSelect(command) {
      const data = this.reportInfo
      if (command == 'edit') {
        this.formAddTitle = '编辑信息'
        this.formAddForm = objDeepCopy(data)
        this.formAddForm.month = data.targetYear + '-' + data.targetMonth
        this.batchId = data.batchId
        this.fileList = data.file || []
        this.formAddRules = baseModel.rule
        this.formAddFields = baseModel.field.filter(item => item.field != 'files')
        this.formAddDialogShow = true
      }
    },
    /**
     * 附件操作
     */
    fileSelect(files, event) {
      for (let index = 0; index < files.length; index++) {
        const file = files[index]
        this.uploadFileRequest(file)
      }
      event.target.value = ''
    },

    /**
     * 文件上传
     */
    uploadFileRequest(file) {
      this.$wkUploadFile.upload({
        request: adminFileUploadAPI,
        file: file,
        params: {
          batchId: this.batchId
        }
      }).then(({ res }) => {
        this.fileList.push(res.data)
        this.batchId = res.data.batchId
      }).catch(() => {})
    },

    fileDelete(data, index) {
      adminFileDeleteByIdAPI(data.fileId).then(res => {
        this.fileList.splice(index, 1)
      }).catch(() => {})
    }

  }
}
</script>

<style lang="scss" scoped>
.base-add-button {
  width: 100%;
  margin: 10px 0;
  padding: 11px 12px;
}

.wk-base-detail-section + .wk-base-detail-section {
  border-top: 1px solid $xr-border-color-base;
}

.create-sections {
  /deep/ .create-sections-content {
    padding: 0 20px;
  }
}

.contract-files {
  width: 80%;
  margin: 20px 0 20px 10px;
}
</style>
